package com.zhq.cxf.config;

import com.zhq.cxf.annotation.EnableAutoPublish;
import com.zhq.cxf.intercept.AuthHeaderIntercept;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;


/**
 * <pre>
 * @class com.zhq.cxf.config.AutoPublishConfig
 * @description 自动发布服务代码支持
 * @author zhq
 * @date 2022/6/2 15:01
 * </pre>
 */
@Slf4j
@Component
public class AutoPublishConfig implements ApplicationRunner {

    @Autowired
    private Bus bus;

    @Autowired
    private WebApplicationContext applicationContext;

    @Autowired
    private AuthHeaderIntercept auth;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        EndpointImpl endpoint;

        String[] beanNames = applicationContext.getBeanNamesForAnnotation(EnableAutoPublish.class);

        try{
            for (String beanName : beanNames) {
                String publishPath = applicationContext.getType(beanName).getAnnotation(EnableAutoPublish.class).publishPath();
                endpoint = new EndpointImpl(bus, applicationContext.getBean(beanName));
                endpoint.publish(publishPath);
                // 添加soapHeader校验拦截器
                endpoint.getInInterceptors().add(auth);
                log.info(String.format("服务发布成功！！beanName: %s, publishPath: %s", beanName, publishPath));
                log.info("自动发布服务完成！！");
            }
        }catch (Exception e){
            log.error("自动发布服务异常！！", e);
        }


    }
}
